package ee.ttu.rakarh.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ee.ttu.rakarh.commands.Command;
import ee.ttu.rakarh.commands.CommandFactory;

public class RequestHandler {
	public static final Logger LOG = Logger.getLogger(RequestHandler.class);
	public String handle(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String actionParam = req.getParameter("a");
		String action = "index";
		CommandFactory commandFactory = new CommandFactory();
		
		if(actionParam == null)
			return action;
		
				
		Boolean loggedIn = commandFactory.processCommand("login").execute(req, res);
		if(!loggedIn){
			action = "login";
			RequestDispatcher dispatcher = req.getRequestDispatcher("login.jsp");
			dispatcher.forward(req, res);
			return action;
		}else{
			req.setAttribute("login", (String)req.getSession().getAttribute("username"));
			if(actionParam.equals("logout")){
				action = "login";
				commandFactory.processCommand("logout").execute(req, res);
				RequestDispatcher dispatcher = req.getRequestDispatcher("login.jsp");
				dispatcher.forward(req, res);
				return action;
			}			
		}
		
		Command command = commandFactory.getCommand(req, res);
		Boolean commandResult = command.execute(req, res);
		
		if(actionParam.equals("kataloog"))
			action = "kataloog";
		
		if(actionParam.equals("addItem"))
			action = "addItem";
		
		if(actionParam.equals("saveItem")){
			action = "addResult";
		}
		if(actionParam.equals("addToStore")){
			action = "addToStore";
		}
		if(actionParam.equals("removeFromStore")){
			action = "removeFromStore";
		}
		if(actionParam.equals("searchItem")){
			action = "searchItem";
		}
		if(actionParam.equals("getCheckInForm")){
			action = "getCheckInForm";
		}
		if(actionParam.equals("getCheckOutForm")){
			action = "getCheckOutForm";
		}
		if(actionParam.equals("getChangeStoreForm")){
			action = "getChangeStoreForm";
		}
		if(actionParam.equals("getUpdateItemForm")){
			action = "getUpdateItemForm";
		}
		if(actionParam.equals("updateItem")){
			action = "updateResult";
		}
		if(actionParam.equals("getItem")){
			action = "getItem";
		}
		if(actionParam.equals("priceList")){
			action = "showPriceList";
		}
		if(actionParam.equals("addPriceListForm")){
			action = "addPriceListForm";
		}
		if(actionParam.equals("searchItemResults")){
			action = "searchItemResults";
		}
		
		LOG.info("action=" + action + " | actionParam=" + actionParam );
		
		return action;
	}
}
